package top.infopub.io.impl;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import top.infopub.io.ContentHandler;
import top.infopub.io.FileLoader;
import top.infopub.io.FileReader;


/**
 * SimpleFileReader
 * @author Awoke
 * @version 2018年9月13日
 * @see SimpleFileReader
 * @since
 */
public class SimpleFileReader extends FileReader {

    final Logger log = LoggerFactory.getLogger(this.getClass());

    public SimpleFileReader(FileLoader fileLoader) {
        super(fileLoader);
    }

    @Override
    public boolean can() {
        return fileLoader.getStream() != null;
    }

    @Override
    protected void parse0(ContentHandler<?> handler) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(fileLoader.getStream(), "gbk"));
            String line = null;
            while ((line = br.readLine()) != null) {
                if (StringUtils.isEmpty(line)) {
                    continue;
                }
                handler.contentHandler(line);
            }
        }
        catch (Exception e) {
            log.error("", e);
        }
        finally {
            fileLoader.releaseAll();
            if (br != null) {
                try {
                    br.close();
                }
                catch (IOException e) {
                    // ignore
                }
            }
        }
    }

}
